package site.sorghum.ddl.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class DdlTableWrap {
    private String name;                                // 表名
    private List<String> pks;                           // 主键列表
    private String remarks;                             // 备注信息
    private List<DdlColumnWrap> columns;                // 列信息
    private List<DdlIndexWrap> indexes;              // 索引信息

    /**
     * 获取索引信息
     *
     * @return 索引信息
     */
    public List<DdlIndexWrap> getIndexes() {
        if (indexes == null) {
            initIndexes();
        }
        return indexes;
    }

    /**
     * 初始化索引信息
     */
    private void initIndexes() {
        indexes = new ArrayList<>();
        Map<Integer, List<DdlColumnWrap>> collected = columns.stream().filter(it -> it.getIndexGroup() != null).collect(Collectors.groupingBy(
                DdlColumnWrap::getIndexGroup,
                Collectors.mapping(it -> it, Collectors.toList())
        ));
        collected.forEach(
                (k, v) -> {
                    DdlColumnWrap first = v.get(0);
                    DdlIndexWrap ddlIndexWrap = new DdlIndexWrap();
                    List<String> columnNames = v.stream().map(DdlColumnWrap::getName).collect(Collectors.toList());
                    ddlIndexWrap.setColumnNames(columnNames);
                    ddlIndexWrap.setUnique(first.isUnique());
                    ddlIndexWrap.setTable(first.getTable());
                    ddlIndexWrap.getIndexName();
                    indexes.add(ddlIndexWrap);
                });
    }
}